require('../less/run.less')
document.ready(function () {
    window.utils.jumpPage('run')
    window.utils.checkPage('run')
    // 获取元素节点
    let runCount = document.querySelector('.runCount') //获取倒计时节点
    let masking = document.getElementById('masking') //获取蒙版节点
    let countDown = document.querySelector('#countDown') //获取蒙版倒计时节点
    let secondMask = document.querySelector('#secondMask') //跑步蒙版
    let suspend = document.querySelector('#suspend') //暂停按钮
    let conPractic = document.querySelector('#conPractic') //继续练习
    let endPractice = document.querySelector('#endPractice') //结束练习
    let doneBtn = document.querySelector('#doneBtn') //完成训练
    let backWards = document.querySelector('#backWards') //返回按钮
    let systemTime = document.querySelector('#systemTime') //系统时间
    let checkMap = document.querySelector('#checkMap') //地图按钮
    let showTime = document.querySelector('#showTime') //用时
    let spendTime = document.querySelector('#spendTime') //用时
    let runDistance = document.querySelector('#runDistance') //跑步距离
    let runSpeed = document.querySelector('#runSpeed') //配速
    let runCalorie = document.querySelector('#runCalorie') //消耗卡路里
    let mapSpeed = document.querySelector('#mapSpeed') //地图速度
    let mapCalorie = document.querySelector('#mapCalorie') //地图消耗卡路里
    let mapDistance = document.querySelector('#mapDistance') //地图距离
    let totalDistance = document.querySelector('#totalDistance') //总距离
    // console.log(mapDistance);
    // 倒计时
    let index = 0
    //第一层蒙版
    runCount.addEventListener('click', function () {
        let arr = [3, 2, 1, 'GO']
        masking.style.display = 'flex';
        let timer = setInterval(function () {
            index++
            if (index >= arr.length) {
                clearInterval(timer)
                secondMask.style.display = 'block'
                masking.style.display = 'none'
                startRunning()
                return
            }
            countDown.innerHTML = arr[index]

        }, 1000)


    })

    //点击地图按钮
    checkMap.addEventListener('click', function () {
        thirdMask.style.display = 'block'
        secondMask.style.display = 'none';

        return
    })
    //点击返回按钮
    backWards.addEventListener('click', function () {
        thirdMask.style.display = 'none'
        secondMask.style.display = 'block';

    })
    // 暂停按钮
    suspend.addEventListener('click', function () {
        suspend.style.display = 'none'; //暂停按钮
        conPractic.style.display = 'flex' //继续练习
        endPractice.style.display = 'flex' //停止练习
        clearInterval(runInterval) //清除计时器
    })
    //点击继续按钮
    conPractic.addEventListener('click', function () {
        endPractice.style.display = 'none'; //结束
        suspend.style.display = 'flex' //暂停
        conPractic.style.display = 'none';
        startRunning()

    })
    //点击结束按钮
    endPractice.addEventListener('click', function () {
        // endPractice.style.display = 'none';
        thirdMask.style.display = 'block';
        secondMask.style.display = 'none'
        backWards.style.display = 'none'
        doneBtn.style.display = 'block'
        geoposiotion() //绘制起点
        let point = new BMap.Point(pointArr[count - 2].lng, pointArr[count - 2].lat)
        window.utils.addMarker(map, point, require('../img/end.png'))
    })
    //显示系统时间
    let d = new Date()
    let year = window.utils.zeroNum(d.getFullYear())
    let month=window.utils.zeroNum(d.getMonth()+1)
    let day=window.utils.zeroNum(d.getDate())
    systemTime.innerHTML=`${year}/${month}/${day}`
    console.log(d,month,day,year);

    //点击完成按钮
    doneBtn.addEventListener('click', function () {
        //发送数据
        window.$http.post('/sports/save', {
            id: JSON.parse(window.localStorage.getItem('userData')).userId,
            type: 1,
            takeTime: total.toFixed(2), //跑步距离
            miles: total / runTime, //平均配速
            averagerate: runTime, //跑步用时
            calorie: ccc, //消耗卡路里
        }, function (res) {
            console.log(res);
            if (res.status == 0) {
                location.href = './run.html'
            } else {
                console.log(res.msg);
            }
        })


    })
    //获取累计运动数据
    //保存累计里程
    let id = JSON.parse(window.localStorage.getItem('userData')).userId
    window.$http.get(`/sports/exerciseData?id=${id}`, function (res) {
        window.localStorage.setItem('sportsData', JSON.stringify(res.data))
        //   console.log(res.data);
    })
    let sportsMiles = JSON.parse(window.localStorage.getItem('sportsData')).miles.toFixed(2)
    totalDistance.textContent = sportsMiles
    //初始化地图
    function initMap() {
        // 百度地图API功能
        var map = new BMap.Map("allmap");
        var geolocation = new BMap.Geolocation(); //创建一个定位对象
        // 开启SDK辅助定位
        geolocation.enableSDKLocation();
        geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) { //获取数据进行de判定
                var mk = new BMap.Marker(r.point); //绘制指定地图位置点图标
                map.addOverlay(mk);
                map.panTo(r.point);
                var point = new BMap.Point(r.point.lng, r.point.lat); //设置地图的中心点
                map.centerAndZoom(point, 12); //渲染指定点的地图及层级
                window.utils.addMarker(map, point, require('../img/cat.jpg'))
            } else {
                alert('获取定位失败');
            }
        });
    }
    //使用初始化地图
    initMap()

    //定义全局变量
    let runTime = 0
    let total = 0 //定义一个变量保存数据
    let runInterval = null //运动的定时器
    let speed = 0 //定义变量保存速度
    let ccc = 0 //定义变量保存卡路里
    //运动的函数
    function startRunning() {
        //定时器
        runInterval = setInterval(function () {
            runTime++; //时间自增
            //添加事件到指定时间
            showTime.textContent = window.utils.formatTime(runTime);
            spendTime.textContent = window.utils.formatTime(runTime);
            geoposiotion() //获取定位,每一秒的经度和纬度
            //获取时间线  
            let sum = 0;
            for (let i = 0; i < pointArr.length - 1; i++) {
                let curPoint = pointArr[i]; //前一个点
                let nextPoint = pointArr[i + 1]; //后一个点
                // console.log(curPoint,nextPoint)
                //calcDistance(lat1, lng1, lat2, lng2)  距离
                //累加距离
                sum += parseFloat(window.utils.calcDistance(curPoint.lat, curPoint.lng, nextPoint.lat, nextPoint.lng))
                //绘制路线 drawLine(map, curPoint, nextPoint) 
                window.utils.drawLine(map, curPoint, nextPoint);
            }
            total = sum
            // console.log(sum);
            runDistance.textContent = sum.toFixed(2); //跑步距离
            mapDistance.textContent = sum.toFixed(2) //地图距离
            //calcPace(d, s)参数:距离和时间
            speed = window.utils.calcPace(sum, runTime)
            runSpeed.textContent = speed //跑步速度
            mapSpeed.textContent = speed //地图速度
            //计算卡路 参数: 跑步的距离calCalorie(miles)
            ccc = window.utils.calCalorie(sum)
            runCalorie.textContent = ccc //跑步消耗卡路里
            mapCalorie.textContent = ccc //地图消耗卡路里
        }, 1000);
    }

    //第二个地图
    var map = new BMap.Map("mapView");
    let interval = 0.0001 //每一次运动的值
    let pointArr = [] //每一次的点
    let count = 0 //运动次数

    //获取坐标点功能
    function geoposiotion() {
        // 百度地图API功能                                      
        var geolocation = new BMap.Geolocation(); //创建一个定位对象
        geolocation.getCurrentPosition(function (r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) { //获取数据进行de判定
                //  var mk = new BMap.Marker(r.point); //绘制指定地图位置点图标
                let lng = r.point.lng + interval //运动后经度
                let lat = r.point.lat + interval //运动后纬度
                map.centerAndZoom(new BMap.Point(lng, lat), 18); //渲染指定点的地图及层级
                //      map.setViewport(pointArr) //设置视图
                interval += 0.0001 //运动的值自增1
                pointArr.push({
                    lng: lng,
                    lat: lat
                })
                // console.log(pointArr,'pointArr')
                count += 1 //运动次数自加1
                //绘制开始的点
                if (pointArr && pointArr.length == 1) {
                    window.utils.addMarker(map, new BMap.Point(pointArr[0].lng, pointArr[0].lat), require('../img/start.png'))
                }

            } else {
                alert('定位失败');
            }
        });

    }


})